<template>
  <div class="photoEdit">
    <div class="toolBar">
      <van-button type="default" size="small" @click="$emit('close')">取消</van-button>
      <van-button type="info" size="small" @click="uploadPhoto">确认</van-button>
    </div>
    <img ref="imgRef" :src="img" />
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  name: 'EditPhoto',
  props: {
    img: {
      type: [String, Object],
      default: null
    }
  },
  data() {
    return {
      cropper: null
    }
  },
  mounted() {
    this.editPhoto()
  },
  methods: {
    editPhoto() {
      this.cropper = new Cropper(this.$refs.imgRef, {
        viewMode: 1,
        dragMode: 'move',
        aspectRatio: 1,
        autoCropArea: 1,
        cropBoxMovable: false,
        cropBoxResizable: false,
        background: false,
        movable: true
      })
    },
    uploadPhoto() {
      this.cropper.getCroppedCanvas().toBlob((blob) => {
        const formData = new FormData()
        formData.append('photo', blob)
        this.$emit('croppedImage', formData)
      })
    }
  }
}
</script>

<style scope lang="less">
.photoEdit {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 10px 0;
  background-color: #000;
  height: 100%;
  .toolBar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    display: flex;
    justify-content: space-between;
    padding: 20px;
    z-index: 10;
  }
  img {
    display: block;
    max-width: 100%;
  }
}
</style>
